package com.hulk.dryad.manage.limiter.filter;

import cn.hutool.core.util.StrUtil;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.util.WebUtils;
import com.hulk.dryad.manage.limiter.constant.LimiterInfo;
import com.hulk.dryad.manage.limiter.expression.LimiterInfoResolver;
import com.hulk.dryad.manage.limiter.strategy.LimiterStrategy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hulk
 * @date 2020/9/13
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LimiterIpFilter extends OncePerRequestFilter {

	private static final String PREFIX = LimiterInfoResolver.LIMIT_NAME_PREFIX + LimiterInfoResolver.LIMIT_NAME_SEPARATOR;

	private LimiterStrategy redisLimiterStrategy;
	public LimiterIpFilter(LimiterStrategy redisLimiterStrategy){
		this.redisLimiterStrategy=redisLimiterStrategy;
	}

	@Value("${limiter.filter.enable:false}")
	private Boolean ipEnable;
	@Value("${limiter.filter.replenish:2}")
	private Integer replenish;
	@Value("${limiter.filter.capacity:5}")
	private Integer capacity;

	@Override
	@SneakyThrows
	public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
		if (!ipEnable) {
			chain.doFilter(request, response);
		} else {

			String ip = WebUtils.getIP(request);
			String keyName = PREFIX + ip;
			LimiterInfo info = new LimiterInfo();
			info.setLimitName(keyName).setReplenish(replenish).setCapacity(capacity);
			boolean b = redisLimiterStrategy.execute(info);
			if (!b) {
				log.warn(keyName+BEC.E_2021.toString());
				WebUtils.renderJson(response, R.failed(BEC.E_2021.getErrCode(), BEC.E_2021.getErrDesc()));
			} else {
				chain.doFilter(request, response);
			}
		}

	}

}
